#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
解密爬虫脚本 - 针对加密响应的网站
基于找到的JavaScript解密逻辑：y_函数使用AES-ECB解密
"""

import requests
import json
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import hashlib
import time
import random
import string

class DecryptSpider:
    def __init__(self, use_proxy=True):
        self.session = requests.Session()
        # 从JavaScript代码中提取的默认密钥
        self.default_key = "GcgzsKdDZTumABNz7uujrCfPIk9TQ355"

        # 设置代理
        if use_proxy:
            proxies = {
                'http': 'http://127.0.0.1:7890',
                'https': 'http://127.0.0.1:7890'
            }
            self.session.proxies.update(proxies)
            print("✅ 已配置代理: 127.0.0.1:7890")

        # 设置请求头
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'Referer': 'https://wmqxz.net/category/jvid',
        })

        # 基础URL
        self.base_url = "https://wmqxz.net"
        
    def generate_device_id(self, length=24):
        """生成随机设备ID"""
        chars = string.ascii_letters + string.digits
        return ''.join(random.choice(chars) for _ in range(length))
    
    def decrypt_response(self, encrypted_data, key=None):
        """
        解密响应数据
        基于JavaScript中的y_函数逻辑：AES-ECB模式解密
        """
        if key is None:
            key = self.default_key
            
        try:
            # 将密钥转换为字节
            key_bytes = key.encode('utf-8')
            
            # Base64解码加密数据
            encrypted_bytes = base64.b64decode(encrypted_data)
            
            # 创建AES解密器 (ECB模式)
            cipher = AES.new(key_bytes, AES.MODE_ECB)
            
            # 解密
            decrypted_bytes = cipher.decrypt(encrypted_bytes)
            
            # 去除填充
            decrypted_bytes = unpad(decrypted_bytes, AES.block_size)
            
            # 转换为字符串
            decrypted_text = decrypted_bytes.decode('utf-8')
            
            return decrypted_text
            
        except Exception as e:
            print(f"解密失败: {e}")
            return None
    
    def make_request(self, url, method='GET', data=None, headers=None):
        """发送请求并尝试解密响应"""
        try:
            if headers:
                request_headers = self.session.headers.copy()
                request_headers.update(headers)
            else:
                request_headers = self.session.headers
                
            if method.upper() == 'POST':
                response = self.session.post(url, json=data, headers=request_headers)
            else:
                response = self.session.get(url, headers=request_headers)
            
            print(f"请求状态码: {response.status_code}")
            print(f"响应长度: {len(response.text)}")
            
            # 尝试直接解析JSON
            try:
                json_data = response.json()
                print("响应是明文JSON")
                return json_data
            except:
                pass
            
            # 尝试解密响应
            response_text = response.text.strip()
            
            # 检查是否是Base64编码的加密数据
            if self.is_base64(response_text):
                print("检测到加密响应，尝试解密...")
                decrypted = self.decrypt_response(response_text)
                
                if decrypted:
                    try:
                        return json.loads(decrypted)
                    except:
                        return decrypted
                        
            return response.text
            
        except Exception as e:
            print(f"请求失败: {e}")
            return None
    
    def is_base64(self, s):
        """检查字符串是否是Base64编码"""
        try:
            if len(s) % 4 == 0:
                base64.b64decode(s, validate=True)
                return True
        except:
            pass
        return False
    
    def list_media(self, category_id="1737018067636858880", page_no=1, media_type=3, order_type="SORT_PUBLISH_WEIGHT"):
        """获取媒体列表"""
        url = f"{self.base_url}/member/media/stationGroup/listMediaBySearchType"

        # 构造请求数据 - 根据你提供的实际载荷格式
        data = {
            "categoryId": category_id,
            "orderType": order_type,
            "mediaType": media_type,
            "pageNo": page_no,
            "pageSize": 20
        }

        # 设置请求头
        headers = {
            'Content-Type': 'application/json;charset=utf-8',
            'language': 'en_US',
            'os': '2',
            'ver': '1.0'
        }

        print(f"获取媒体列表: 分类ID={category_id}, 页码={page_no}, 媒体类型={media_type}")
        result = self.make_request(url, method='POST', data=data, headers=headers)

        return result
    
    def get_media_detail(self, media_id):
        """获取媒体详情"""
        url = f"{self.base_url}/member/media/detail"
        
        data = {
            "mediaId": media_id
        }
        
        headers = {
            'Content-Type': 'application/json;charset=utf-8',
        }
        
        print(f"获取媒体详情: {media_id}")
        result = self.make_request(url, method='POST', data=data, headers=headers)
        
        return result
    
    def test_decrypt(self):
        """测试解密功能"""
        # 这里可以放一些已知的加密数据进行测试
        test_encrypted = "your_test_encrypted_data_here"
        
        if test_encrypted != "your_test_encrypted_data_here":
            result = self.decrypt_response(test_encrypted)
            print(f"测试解密结果: {result}")
        else:
            print("没有测试数据，跳过解密测试")

def main():
    """主函数"""
    spider = DecryptSpider()
    
    print("=== 解密爬虫测试 ===")
    
    # 测试解密功能
    spider.test_decrypt()
    
    # 测试搜索功能
    print("\n=== 测试搜索功能 ===")
    search_result = spider.search_media("测试", page=1)
    
    if search_result:
        print("搜索结果:")
        print(json.dumps(search_result, ensure_ascii=False, indent=2))
    else:
        print("搜索失败")
    
    print("\n=== 完成 ===")

if __name__ == "__main__":
    main()
